package com.zhou.app.favourite.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.zhou.app.favourite.entity.FavIcon;
import com.zhou.app.favourite.service.service.impl.FavIconServiceImpl;
import com.zhou.common.lib.model.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Api(tags = "网站图标")
@ApiSupport(order = 284)
@RestController
@RequestMapping("/favourite/icon")
public class FavIconController {

    @Autowired
    private FavIconServiceImpl favIconService;


    @GetMapping(value = "", produces = MediaType.IMAGE_JPEG_VALUE)
    public byte[] getIcon(@RequestParam String host, HttpServletResponse response) {
        byte[] result = null;
        LambdaQueryWrapper<FavIcon> queryWrapper = Wrappers.<FavIcon>lambdaQuery()
                .eq(FavIcon::getHost, host);
        FavIcon icon = favIconService.getOne(queryWrapper);
        if (icon != null) {
            result = icon.getIcon();
        }
        return result;
    }

    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "新增图片")
    @PostMapping("/")
    public Response uploadImage(@RequestParam("file") MultipartFile file, String originPath) throws IOException {
        favIconService.uploadImage(file, originPath);
        return Response.success();
    }
}
